import pickle
import random
import re
from collections import namedtuple
from typing import Any, Optional
from pathlib import Path

import numpy as np
import pandas as pd
from src.norm import *
from util import *

TEMPPATH = Path('../data/temp')
INFOPATH = TEMPPATH.joinpath('info')
HOOKDATAPATH = '../data/temp/hookdata.pkl'

def hookdata_decorator(n_hook=10):
    hookdata = HookData()
    n = 0
    def do_result(result, *args, **kwargs):
        nonlocal hookdata, n
        if n < n_hook:
            origin_data:np.ndarray = args[0]  # 第一个位置参数
            target_data:np.ndarray = result  # 返回值
            ind = random.randint(0, len(origin_data)-1)
            y, new_y = origin_data[ind], target_data[ind]
            x, new_x = range(len(y)), range(len(new_y))
            hookdata.add(x, y, f'input_{ind}').add(new_x, new_y, f'output_{ind}')
            n += 1
        elif n == n_hook:
            hookdata.save()
        return result
    return FunctionDecoratorFactory(do_result=do_result)()

class HookData:
    data = namedtuple('data', ['x', 'y', 'id'])
    def __init__(self) -> None:
        self._x = []
        self._y = []
        self._id = []

    def add(self, x:Any, y:Any, id_:Optional[str]=None):
        self._x.append(x)
        self._y.append(y)
        if id_:self._id.append(id_)
        return self
    
    def get(self):
        return self.data(self._x, self._y, self._id)
    
    def load(self):
        with open(HOOKDATAPATH, 'rb') as f:
            data:HookData = pickle.load(f)
            self.__dict__ = data.__dict__

    def save(self):
        with open(HOOKDATAPATH, 'wb') as f:
            pickle.dump(self, f)

def version_difference(vf:str, vb:str):
    '''比较版本差异'''
    vf_files = NameSpace(INFOPATH)._search_named_file(vf)
    vb_files = NameSpace(INFOPATH)._search_named_file(vb) 
    pattern = r'/test_v[\d\.]+.csv'   
    for i, j in itertools.product(vf_files, vb_files):
        if re.search(pattern, i) and re.search(pattern, j):
            df1, df2 = map(lambda x:pd.read_csv(x, header=None), [i, j])
            df3 = pd.merge(df1, df2, how='inner')
            print(len(df3)/len(df1))
            print(len(df3)/len(df2))
            break

if __name__ == '__main__':
    version_difference('v2', 'v2.1')
    # hookdata = HookData()
    # hookdata.load()
    # data = hookdata.get()
    # print(data.x)
    # print(data.id)
